package handler

import (
	"google.golang.org/protobuf/reflect/protoreflect"
	"google.golang.org/protobuf/types/dynamicpb"
	"sen-golang-study/go_game_study/hero_story_go_server/biz_server/base"
	"sen-golang-study/go_game_study/hero_story_go_server/biz_server/service/login/loginsrv"
	"sen-golang-study/go_game_study/hero_story_go_server/biz_server/service/user/userdata"
	"sen-golang-study/go_game_study/hero_story_go_server/common/log"
	"sen-golang-study/go_game_study/hero_story_go_server/common/server_msg/proto_msg"
)

// 用户登录指令处理器
func handleCmdUserLogin(ctx CmdContext, pbMsgObj *dynamicpb.Message) {
	if nil == ctx ||
		nil == pbMsgObj {
		return
	}

	userLoginCmd := &proto_msg.UserLoginCmd{}

	pbMsgObj.Range(func(f protoreflect.FieldDescriptor, v protoreflect.Value) bool {
		userLoginCmd.ProtoReflect().Set(f, v)
		return true
	})

	log.Info(
		"收到用户登录消息! userName = %s, password = %s",
		userLoginCmd.GetUserName(),
		userLoginCmd.GetPassword(),
	)

	// 根据用户名称和密码登录
	bizResult := loginsrv.LoginByPasswordAsync(userLoginCmd.GetUserName(), userLoginCmd.GetPassword())

	if nil == bizResult {
		log.Error(
			"业务结果返回空值, userName = %s",
			userLoginCmd.GetUserName(),
		)
		return
	}

	bizResult.OnComplete(func() {
		complete(ctx, userLoginCmd, bizResult)
	})
}

func complete(ctx CmdContext, userLoginCmd *proto_msg.UserLoginCmd, bizResult *base.AsyncBizResult) {
	returnedObj := bizResult.GetReturnedObj()

	if nil == returnedObj {
		log.Error(
			"用户不存在, userName = %s",
			userLoginCmd.GetUserName(),
		)
		return
	}

	user := returnedObj.(*userdata.User)

	userLoginResult := &proto_msg.UserLoginResult{
		UserId:     user.UserId,
		UserName:   user.UserName,
		HeroAvatar: user.HeroAvatar,
	}

	ctx.BindUserId(user.UserId)
	ctx.Write(userLoginResult)
}
